<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <title>用户管理列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="/js/jquery-3.7.1.min.js"></script>
    <style>
        .queryBox{
            display: flex;
            margin: 10px 0;
            border-radius: 10px;
            border: solid 1px #aaaaaa;
            padding: 10px;
        }
    </style>
</head>

<body>
<div style="padding: 16px;">
    <div class="layui-card">
        <h1  style="color: black;font-size: 16px;padding: 20px">用户信息管理</h1>
        <div class="queryBox">
            <form   class="layui-form" id="queryForm" >
                <ul class="query-inline" style="display: flex">
                    <li class="layui-input-group">
                        <div class="layui-input-prefix">
                            姓名
                        </div>
                        <input type="text" class="layui-input" name="nameFuzzy">
                    </li>

<!--                    <li class="layui-input-group">-->
<!--                        <div class="layui-input-prefix">-->
<!--                            电话-->
<!--                        </div>-->
<!--                        <input type="text" class="layui-input" name="phoneFuzzy">-->
<!--                    </li>-->

<!--                    <li class="layui-input-group">-->
<!--                        <div class="layui-input-prefix">-->
<!--                            邮箱-->
<!--                        </div>-->
<!--                        <input type="text" placeholder="支持模糊查询" class="layui-input" name="emailFuzzy">-->
<!--                    </li>-->

                    <li class="layui-input-group">
                        <button type="button" class="layui-btn lay-btn-sm layui-btn-normal "
                               id="searchBtn" style="margin-left: 20px">
                            查询
                        </button>
                    </li>
                    <li class="layui-input-group">
                        <button type="button"  class="layui-btn layui-bg-red"
                                id="addButton" style="margin-left: 20px">
                            新增
                        </button>
                    </li>

<!--                    <li class="layui-input-group">-->
<!--                        <button type="button"  class="layui-btn layui-bg-green"-->
<!--                                id="delBatchBtn" style="margin-left: 20px">-->
<!--                           批量删除-->
<!--                        </button>-->
<!--                    </li>-->
                    <button type="button" class="layui-btn layui-btn-normal layui-bg-red"
                            id="delBatchBtn" style="margin-left: 20px ">
                        <i class="layui-icon layui-icon-delete"></i>
                    </button>
                </ul>
            </form>
        </div>
        <div class="layui-card-body">
            <table class="layui-hide" id="userList" lay-filter="userList"></table>
        </div>
    </div>

    <div class="addInfo" id="addInfo" style="display: none;margin: 10px ">
        <form  class="layui-form layui-form-pane" id="addInfoForm" >
            <div class="layui-form-item">
                <input type="hidden" name="userId">
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-block">
                    <input type="text" name="name" autocomplete="off" placeholder="请输入姓名" lay-verify="required" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">学工号</label>
                <div class="layui-input-block">
                    <input type="text" name="stuJobNo" autocomplete="off" placeholder="请输入学号" lay-verify="required" class="layui-input">
                </div>
            </div>
<!--            <div class="layui-form-item" id="password" style="display: block">-->
<!--                <label class="layui-form-label">密码</label>-->
<!--                <div class="layui-input-block">-->
<!--                    <input type="text" name="password" autocomplete="off" placeholder="请输入密码" lay-verify="required" class="layui-input">-->
<!--                </div>-->
<!--            </div>-->

            <div class="layui-form-item">
                <label class="layui-form-label">角色类型</label>
                <div class="layui-input-block">
                    <select lay-verify="required" name="roleType">
                        <option value="0">学生</option>
<!--                        <option value="1">教师</option>-->
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <button class="layui-btn" lay-submit lay-filter="submit4User">确认</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </form>
    </div>
</div>

<script type="text/html" id="toolTemplate">
    <div class="layui-clear-space">

        <a class="layui-btn layui-btn-xs" lay-event="edit">
            编辑
        </a>

        <a class="layui-btn layui-btn-xs layui-bg-red" lay-event="del">
            删除
        </a>
<!--        <a class="layui-btn layui-btn-xs layui-bg-red" lay-event="restPwd">-->
<!--            重置密码-->
<!--        </a>-->
    </div>
</script>

<script type="text/javascript">

    // 编辑框
    layui.use(['form', 'layer'], function() {

    });

    // 关闭弹出层
    const closeAddInfoDialog=()=> {
        if (layerIndex !== undefined) {
            layer.close(layerIndex);
            layerIndex = undefined; // 重置索引值
        }
    }

    // 获取查询输入值
     const getSearchCondition=()=> {
        let formData={};
        // 遍历输入元素，将值存储到formData中
        $("#queryForm").find('input',"select").each(function () {
            let name=$(this).attr('name'); // 获取元素的 name属性
            let value=$(this).val(); // 获取元素的值

            // 只有name 值存在且不为空 才会添加到formData中
            if(name&&value){
                formData[name]=value;
            }
        });
        return formData;
    }

    // 搜索
    const search=()=>{
        let queryData=getSearchCondition();
        const table=layui.table;
        table.reloadData("userList",{
            where:{data:queryData}
        });
        console.log("where condition:"+JSON.stringify(queryData));
    }
    // 为新增按钮绑定该事件
    document.getElementById('searchBtn').addEventListener('click', function() {
        search();
    });

    // 删除数据
     const delData=()=>{
        layui.use(['layer','popup' ], function() {
            let layer = layui.layer;
            let popup=layui.popup;
            let table=layui.table;
            let checkStatus = table.checkStatus("userList"); // teacher 表格id  或者filter id
            let ids = checkStatus.data.map(item=>item.userId).join(",");
            if(ids.length===0){
                popup.warning("请选择要删除的信息");
                return;
            }
            layer.confirm("确定要删除吗", {icon: 3}, function(index){
                let request = $.ajax({
                    url: "/admin/delInfo?userId="+ids,
                    method: "POST",
                });
                request.done(function( res ) {
                    if(res.code===200){
                        popup.success(res.info);
                        search();
                    }else{
                        popup.warning(res.info);
                    }
                    layer.close(index);
                    // 重新加载数据
                    search()
                });
                request.fail(function( jqXHR, textStatus ) {
                    console.error(jqXHR,textStatus);
                });
            }, function(index){
                layer.msg("取消成功", {icon: 1});
                layer.close(index);
            });
        });
    }
    // 为新增按钮绑定该事件
    document.getElementById('delBatchBtn').addEventListener('click', function() {
        delData();
    });


    const  resetPwd=(data)=>{
        layui.use(['layer','popup' ], function() {
            let layer = layui.layer;
            let popup=layui.popup;
            layer.confirm("确定重置【"+data.name+"】的密码吗？", {icon: 3}, function(index){
                let request = $.ajax({
                    url: "/admin/resetPwd?userId="+data.userId,
                    method: "POST",
                });
                request.done(function( res ) {
                    if(res.code===200){
                        popup.success(data.info);
                        search();
                    }else{
                        popup.warning(data.info);
                    }
                    layer.close(index);
                });
                request.fail(function( jqXHR, textStatus,responseJSON) {
                    console.error(jqXHR,textStatus,);
                    popup.warning(responseJSON.error);
                });
            }, function(index){
                layer.msg("取消成功", {icon: 1});
                layer.close(index);
            });
        });
    }

    const submitUserForm=(form,popup)=>{
        // 提交事件
        form.on('submit(submit4User)', function(data){
            var field = data.field; // 获取表单字段值
            var request = $.ajax({
                url: "/admin/saveInfo",
                method: "POST",
                data: field,
                dataType: "json"
            });
            request.done(function( data ) {
                if(data.code===200){
                    popup.success(data.info);
                    closeAddInfoDialog();
                    search();
                }else {
                    popup.warning(data.info);
                }

            });
            request.fail(function( jqXHR, textStatus ) {
                popup.warning(data.info);
                console.error(jqXHR,textStatus);
            });
            return false; // 阻止默认 form 跳转
        });
    }

    // layui use
    layui.use(['admin','jquery','popup','table','form'], function() {
        let popup = layui.popup;
        let $ = layui.jquery;
        let table=layui.table;
        let form = layui.form;
        let layer = layui.layer;

        // 1.校验表单是否合法
        submitUserForm(form,popup);

        const showEdit = (type, data) => {
            // 重置表单
            const resetForm = () => {
                $("#addInfo").find('input, select').each(function () {
                    $(this).val(''); // 清空输入框和选择框的值
                    if (this.type === 'checkbox' || this.type === 'radio') {
                        this.checked = false; // 重置复选框和单选按钮
                    }
                });
            };
            // 填充表单数据
            const fillFormData = (formData) => {
                Object.keys(formData).forEach(key => {
                    // 使用 document.querySelector 或 jQuery 的 $() 来选择 DOM 元素
                    const element = document.querySelector(`#addInfoForm [name="${key}"]`);
                    if (!element) {
                        return;
                    }

                    if (element.type === 'checkbox' || element.type === 'radio') {
                        element.checked = formData[key];
                    } else if (element.tagName.toLowerCase() === 'select') {
                        if (element.multiple) {
                            // 对于多选 select，需要遍历所有选项并根据数据设置 selected 属性
                            const values = Array.isArray(formData[key]) ? formData[key] : [formData[key]];
                            for (let option of element.options) {
                                option.selected = values.includes(option.value);
                            }
                        } else {
                            // 对于单选 select，直接设置 value 即可
                            element.value = formData[key] || '';
                        }
                        // 重新渲染 select 组件
                        form.render('select');
                    } else {
                        element.value = formData[key];
                    }
                });
                // 重新渲染其他表单组件
                form.render();
            };
            if (type === 'add') {
                console.log("点击新增");
                resetForm();
                $("#password").css("display", "block");
                layerIndex = layer.open({
                    type: 1,
                    title: "新增信息",
                    area: ['520px', 'auto'],
                    shade: false,  // 禁用遮罩层
                    content: $("#addInfo"),
                    success: function(layero, index) {
                        // 确保表单元素可见后再调用 form.render()
                        setTimeout(() => {
                            form.render();
                        }, 0);
                    }
                });
            } else {
                layerIndex = layer.open({
                    type: 1,
                    title: "修改信息",
                    shade: false,  // 禁用遮罩层
                    area: ['580px', 'auto'],
                    content: $("#addInfo"), // 直接传递 DOM 元素
                    success: function(layero, index) {

                        // 将初始数据应用到表单字段中
                        if (data) {
                            fillFormData(data);
                        }
                        // 不设置密码
                        $("#password").css("display", "none");

                        // 确保表单元素可见后再调用 form.render()
                        setTimeout(() => {
                            form.render();
                        }, 0);

                        console.log('弹出层已打开');
                    }
                });
            }
        };
        // 为新增按钮绑定该事件
        document.getElementById('addButton').addEventListener('click', function() {
            showEdit('add', {});
        });


        // 1. 获取数据
        $(document).ready(function () {

            let cols4UserList = [
                { type: 'checkbox', fixed: 'left' },
                { field: 'stuJobNo', fixed: 'left', width: 120, title: '学工号'},
                // { field: 'username', fixed: 'left', width: 100, title: '用户名'},
                { field: 'name',  title: '姓名' },
                // // { field: 'nickName', title: '用户昵称'},
                // { field: 'email', title: '邮箱', hide: 0, width: 120},
                // { field: 'phone', title: '电话', hide: 0, width: 120},
                { field: 'sex',  title: '性别',
                    templet: d=> d.sex===0? '女':(d.sex===1?'男':'未知')},
                // { field: 'signature', title: '签名', edit: 'textarea', minWidth: 200, expandedWidth: 200},
                { field: 'createTime', title: '入学时间', width: 160 },
                { fixed: 'right', title: '操作', width: 200, minWidth: 125, toolbar: '#toolTemplate' }
            ];
            let queryData = getSearchCondition();
            // 表格相关事件
            table.render({
                elem: '#userList',
                url: '/admin/loadUserList',
                cols: [cols4UserList],
                method:"post",
                page: true,
                contentType:'application/json',
                where:{'data':queryData},
                defaultToolbar: ['filter', 'exports', 'print', {
                    title: '提示',
                    layEvent: 'LAYTABLE_TIPS',
                    icon: 'layui-icon-tips'
                }],
                limits: [10, 20, 30, 40, 50],
                limit: 10,
                height: 'full-220'
            });
            // 点击编辑事件
            table.on('tool(userList)',function (obj) {
                var  data=obj.data;
                if (obj.event ==='edit'){
                    showEdit('edit',data);
                }else if (obj.event==='del'){
                    delData();
                }else if(obj.event==="restPwd"){
                    resetPwd(data);
                }
            })
        });
    });

</script>
</body>

</html>